package com.mercadoutils.controller;


import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.Meli;
import com.mercadoutils.listeners.SesionListener;


@Controller
public class AuthController{	
	
	private Meli m = new Meli(8617768438635034L, "t7XhJxUeW4HYf2Ii6p4FHyvNpddZ6tDW");
	private String redirectUrl = m.getAuthUrl("http://localhost:8080/MercadoUtils/auth.html");
	 
	@RequestMapping("/auth.html")
	 public String doRedirect(@RequestParam("code") String code,Model model) throws AuthorizationFailure
	 {
		 if (code.equals("noAuth"))
			 return "redirect:"+redirectUrl;
		 else{
				 m.authorize(code, "http://localhost:8080/MercadoUtils/auth.html");
				 HttpSession sesion = SesionListener.getSession();
				 sesion.setAttribute("meli", m);
				 return "redirect:/home.html";
		 }
	 }

}
